package hanlder

import (
	"design-flow/model"
	"design-flow/pkg"
	"github.com/gin-gonic/gin"
	"strconv"
)

func Add(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	data := model.User{
		Username: username,
		Password: pkg.Md5(password),
	}
	err := model.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	data := model.User{
		Username: username,
		Password: pkg.Md5(password),
	}
	model.DB.Where("username=?", username).First(&data).Debug()
	if data.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	token := pkg.TokenHandler(strconv.Itoa(int(data.ID)))
	c.JSON(200, gin.H{
		"code":  200,
		"token": token,
		"msg":   "登录成功",
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	var user []model.User
	model.DB.Offset(offset).Limit(size).Find(&user)

	c.JSON(200, gin.H{
		"code": 200,
		"data": user,
		"msg":  "展示成功",
	})
	return
}
